//Copyright (C) 2009 Ron Coleman. Contact: ronncoleman@gmail.com
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 3 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this library; if not, write to the Free Software
//Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

package org.workplicity.android.cia.ui;

import org.workplicity.android.cia.R;
import org.workplicity.android.cia.application.ELogApplication;
import org.workplicity.android.cia.ui.elogfragments.CatchEditFragment;
import org.workplicity.android.cia.ui.elogfragments.CommentEditMainFragment;
import org.workplicity.android.cia.ui.elogfragments.LogEditFragment;
import org.workplicity.elog.entry.Elog;
import org.workplicity.elog.entry.ElogUser;
import org.workplicity.entry.User;
import org.workplicity.util.Helper;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.PendingIntent;
import android.app.ActionBar.Tab;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;

/**
 * @author brian.gormanly
 */

public class ElogEditActivity extends Activity {
	
	private static final int NOTIFICATION_DEFAULT = 1;
    private static final String ACTION_DIALOG = "org.workplicity.android.cia.ui.action.DIALOG";

	private View mActionBarView;
	private int mThemeId = -1;
	
	ELogApplication app;
	
	// Controls
	EditText logEditOwner;
	EditText logEditId;
	EditText logEditWO;
	Spinner typeSpinner;
	Spinner statusSpinner;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		app = (ELogApplication)getApplication();
		 
		if(savedInstanceState != null && savedInstanceState.getInt("theme", -1) != -1) {
			 mThemeId = savedInstanceState.getInt("theme");
			 this.setTheme(mThemeId);
	    }
		else {
			 // default
			 this.setTheme(R.style.AppTheme_Light);
		}
		
		setContentView(R.layout.elogedit);
	        
        ActionBar bar = getActionBar();
        
        // get the resourcess available
        Resources res = getResources();

        bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        
        // Get the string array that has the tabs / names
        String[] tabNames = res.getStringArray(R.array.eltab_array);
        
        ActionBar.Tab tabA = bar.newTab().setText(tabNames[0]);
        //ActionBar.Tab tabB = bar.newTab().setText(tabNames[1]);
        //ActionBar.Tab tabC = bar.newTab().setText(tabNames[2]);
        ActionBar.Tab tabD = bar.newTab().setText(tabNames[3]);
        ActionBar.Tab tabE = bar.newTab().setText(tabNames[4]);

        Fragment logEditFrag = new LogEditFragment();
        //Fragment handoffEditFrag = new HandoffEditFragment();
        //Fragment linkEditFrag = new LinkEditFragment();
        Fragment commentEditFrag = new CommentEditMainFragment();
        Fragment catchEditFrag = new CatchEditFragment();
        
        tabA.setTabListener(new MyTabListener(logEditFrag));
        //tabB.setTabListener(new MyTabListener(handoffEditFrag));
        //tabC.setTabListener(new MyTabListener(linkEditFrag));
        tabD.setTabListener(new MyTabListener(commentEditFrag));
        tabE.setTabListener(new MyTabListener(catchEditFrag));
        

        mActionBarView = getLayoutInflater().inflate(R.layout.action_bar_elog, null);

        bar.setCustomView(mActionBarView);
        bar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_USE_LOGO);
        bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        bar.setDisplayShowHomeEnabled(true);
        
        bar.addTab(tabA);
        //bar.addTab(tabB);
        //bar.addTab(tabC);
        bar.addTab(tabD);
        bar.addTab(tabE);
        
        // initailize the controls
        logEditOwner = (EditText)findViewById(R.id.logEditOwner);
        logEditId = (EditText)findViewById(R.id.logEditId);
        logEditWO = (EditText)findViewById(R.id.logEditWO);
        
        // check to see what mode we are in and change whether the fields are editable
        if(!app.isCreateMode()) {
        	logEditOwner.setKeyListener(null);
        	logEditId.setKeyListener(null);
        	logEditWO.setKeyListener(null);
        	
        }
        else {
        	logEditOwner.setKeyListener(null);
        	logEditId.setKeyListener(null);
        }
        
        refresh();

	}
	
	public void refresh() {
		// get the edittext info and populate
		User thisUser = Helper.whoAmI(this.app.getContext());
		logEditOwner.setText(thisUser.getLogname());
		
		// check to see if we are editing an existing elog
		if(!app.isCreateMode()) {
			logEditId.setText(app.getCurrentElog().getId().toString());
			logEditWO.setText(app.getCurrentElog().getRequestId().toString());
		}
		else {
			// user selected create mode set the id number to n/a
			logEditId.setText("N/A");
		}
		// get the types available
        
		
		// Type spinner
		String[] types = new String[3];
        types[0] = Elog.Type.NORMAL.toString();
        types[1] = Elog.Type.UNUSUAL.toString();
        types[2] = Elog.Type.SUMMARY.toString();
        
        typeSpinner = (Spinner) findViewById(R.id.typeSpinner);
        ArrayAdapter<String> typeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, types);
        typeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        typeSpinner.setAdapter(typeAdapter);
        typeSpinner.setOnItemSelectedListener(new ActionBarSpinnersListener());
        
        // Status spinner
        String[] statuses = new String[2];
        statuses[0] = Elog.Status.NOTDONE.toString();
        statuses[1] = Elog.Status.DONE.toString();
        
        statusSpinner = (Spinner) findViewById(R.id.statusSpinner);
        ArrayAdapter<String> statusAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, statuses);
        statusAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        statusSpinner.setAdapter(statusAdapter);
        statusSpinner.setOnItemSelectedListener(new ActionBarSpinnersListener());
        
        if(!app.isCreateMode()) {
	        // find the index of the spinner for the type
	        for(int i=0; i<types.length; i++) {
	        	if(types[i] == app.getCurrentElog().getType().toString()) {
	        		typeSpinner.setSelection(i);
	        	}
	        }
	        
	        // find the index of the spinner for the status
	        for(int i=0; i<statuses.length; i++) {
	        	if(statuses[i] == app.getCurrentElog().getStatus().toString()) {
	        		statusSpinner.setSelection(i);
	        	}
	        }
        }
        
		if(app.getCurrentElog() != null) {
			// modifying an existing elog, populate the fields
			// get the elog fragment and refresh it

	        
		}
	}
	
	public ELogApplication getApp() {
		return app;
	}


	public void setApp(ELogApplication app) {
		this.app = app;
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.elogs_menu, menu);
        return true;
    }
	
	
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

        case R.id.saveElog:
            /**
             * Write the current elog back to the server if it is dirty
             */
        	
        	// check to see if it is dirty 
        	if(app.getCurrentElogDirty()) {
        		// check to see if this is a new elog
        		
        		// get the user as an elog user
        		ElogUser thisUser = (ElogUser) Helper.whoAmI(app.getContext());
        		
        		if(ElogEditActivity.this.app.getCurrentElog().getId() == -1) {
        			// check to see if the user completed the neccassary fields
        			// repository title     			
        			this.app.getCurrentElog().setReposTitle(thisUser.getReposTitle());
        			
        			// create user id
        			this.app.getCurrentElog().setCreateUserId(thisUser.getId());
        			
        			// create date
        			// STUB  is this editable???
        		}
        		else {
        			// modify user id
        			this.app.getCurrentElog().setUpdateUserId(thisUser.getId());
        		}
        		
        		// get the type and status
        		setStatusAndType();
        		
        		// elog is dirty and need to be saved
        		SaveElog save = new SaveElog();
        		save.execute();
        		
        	}
        	else {
        		// no changes to elog were made, nothing to do.
        	}

        	showExitDialog("This will be a dialog to confirm saving the changes made. Or noting if there are no new changes and explaining that the record will not be updated in that case.");
            return true;
            
        case R.id.revertElog:
        	showExitDialog("This will be a dialog warning you to save if any changes were made!");
        	return true;


        case R.id.toggleTheme2:
            if (mThemeId == R.style.AppTheme_Dark) {
                mThemeId = R.style.AppTheme_Light;
            } else {	
                mThemeId = R.style.AppTheme_Dark;
            }
            this.recreate();
            return true;

        case R.id.showHelpDialog2:
            showDialog("CIAElog is a branch of Workplicity.\nThis is an example help dialog box that will contain information on how to use the screen you are looking at.");
            return true;
            
        case R.id.showAboutDialog2:
            showDialog("CIAElog is a branch of Workplicity.\nAndroid Client for CIAElog Version 1.0\n\nContributors:\nBrian Gormanly");
            return true;

        default:
            return super.onOptionsItemSelected(item);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        if (ACTION_DIALOG.equals(intent.getAction())) {
            showDialog(intent.getStringExtra(Intent.EXTRA_TEXT));
        }
    }

    void showDialog(String text) {
        // DialogFragment.show() will take care of adding the fragment
        // in a transaction.  We also want to remove any currently showing
        // dialog, so make our own transaction and take care of that here.
        FragmentTransaction ft = getFragmentManager().beginTransaction();

        DialogFragment newFragment = MyDialogFragment.newInstance(text);

        // Show the dialog.
        newFragment.show(ft, "Exit");
    }
    
    void showExitDialog(String text) {
        // DialogFragment.show() will take care of adding the fragment
        // in a transaction.  We also want to remove any currently showing
        // dialog, so make our own transaction and take care of that here.
        FragmentTransaction ft = getFragmentManager().beginTransaction();

        DialogFragment newFragment = MyExitDialogFragment.newInstance(text);

        // Show the dialog.
        newFragment.show(ft, "Exit");
    }

    void showNotification(boolean custom) {
        
    }

    PendingIntent getDialogPendingIntent(String dialogText) {
        return PendingIntent.getActivity(
                this,
                dialogText.hashCode(), // Otherwise previous PendingIntents with the same
                                       // requestCode may be overwritten.
                new Intent(ACTION_DIALOG).putExtra(Intent.EXTRA_TEXT, dialogText).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        
        return true;
    }

    @Override
    public void onSaveInstanceState (Bundle outState) {
        super.onSaveInstanceState(outState);
        //ActionBar bar = getActionBar();
        //int category = bar.getSelectedTab().getPosition();
        //outState.putInt("category", category);
        //outState.putInt("theme", mThemeId);
    }
    
    public static class MyDialogFragment extends DialogFragment {

        public static MyDialogFragment newInstance(String title) {
            MyDialogFragment frag = new MyDialogFragment();
            Bundle args = new Bundle();
            args.putString("text", title);
            frag.setArguments(args);
            return frag;
        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            String text = getArguments().getString("text");

            return new AlertDialog.Builder(getActivity()).setTitle("CIAElog Ver. 1")
	            .setMessage(text)
	            .setPositiveButton(android.R.string.ok,
                    new DialogInterface.OnClickListener() {
                        @Override
						public void onClick(DialogInterface dialog, int whichButton) {
                        }
                    }).create();
        }
    }
    
    public static class MyExitDialogFragment extends DialogFragment {

        public static MyExitDialogFragment newInstance(String title) {
            MyExitDialogFragment frag = new MyExitDialogFragment();
            Bundle args = new Bundle();
            args.putString("text", title);
            frag.setArguments(args);
            return frag;
        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            String text = getArguments().getString("text");

            return new AlertDialog.Builder(getActivity()).setTitle("CIAElog Ver. 1")
                    .setMessage(text)
                    .setPositiveButton(android.R.string.ok,
                            new DialogInterface.OnClickListener() {
                                @Override
								public void onClick(DialogInterface dialog, int whichButton) {
                                	getActivity().finish();
                                }
                            }).create();
        }
    }
    
    public class ActionBarSpinnersListener implements OnItemSelectedListener {

        public void onItemSelected(AdapterView<?> parent,
            View view, int pos, long id) {

        	setStatusAndType();
        }

        

		public void onNothingSelected(AdapterView parent) {
          // Do nothing.
        }
    }
	 
    private void setStatusAndType() {
		// TODO Auto-generated method stub
    	// get the selected type from the spinner and set the current elog to match
        if(typeSpinner.getSelectedItem().toString() == Elog.Type.NORMAL.toString()) {
        	app.setCurrentElogDirty(true);
        	app.getCurrentElog().setType(Elog.Type.NORMAL);
        }
        else if(typeSpinner.getSelectedItem().toString() == Elog.Type.UNUSUAL.toString()) {
        	app.setCurrentElogDirty(true);
        	app.getCurrentElog().setType(Elog.Type.UNUSUAL);
    	}
        else if(typeSpinner.getSelectedItem().toString() == Elog.Type.SUMMARY.toString()) {
        	app.setCurrentElogDirty(true);
        	app.getCurrentElog().setType(Elog.Type.SUMMARY);
    	}
        else {
        	
        }
        
        // get the selected status from the spinner and set the current elog to match
        if(statusSpinner.getSelectedItem().toString() == Elog.Status.DONE.toString()) {
        	app.setCurrentElogDirty(true);
        	app.getCurrentElog().setStatus(Elog.Status.DONE);
        }
        else if(statusSpinner.getSelectedItem().toString() == Elog.Status.NOTDONE.toString()) {
        	app.setCurrentElogDirty(true);
        	app.getCurrentElog().setStatus(Elog.Status.NOTDONE);
    	}
        else {
        	
        }
	}
    
    
 
	 
	 protected class MyTabListener implements ActionBar.TabListener {
        private Fragment myFragment;

        // Called to create an instance of the listener when adding a new tab
        public MyTabListener(Fragment fragment) {
            myFragment = fragment;
        }

        @Override
		public void onTabSelected(Tab tab, FragmentTransaction ft) {
            ft.add(R.id.logfragments, myFragment, null);
        }

        @Override
		public void onTabUnselected(Tab tab, FragmentTransaction ft) {
            ft.remove(myFragment);
        }

        @Override
		public void onTabReselected(Tab tab, FragmentTransaction ft) {
            // do nothing
        }

    }
	 
	 /**
	  * @author Brian Gormanly
	  * @version 1.0
	  * 
	  * <p>AsyncTask that inserts / updates elog</p>
	  * 
	  */
	class SaveElog extends AsyncTask<Void, Void, Integer> {
		@Override
		protected Integer doInBackground(Void... params) {
			try {
				Looper.myLooper();
				Looper.prepare();
			}
			catch(Exception e) {
				// Looper only needs to be created if the thread is new, if reusing the thread we end up here
			}
			
			try {
				String repos = app.getCurrentElog().getReposTitle();
				Helper.insert(app.getCurrentElog(), repos, app.getContext());
				return 1;
			}
			catch(Exception e) {
				return 0;
			}
			
		}
		protected void onPostExecute(Integer success) {
			if(success > 0) {
				
			}
		}
	}

}
